import axios from 'axios'
import { chunk } from 'lodash/array.js'

const BASE_URL = 'https://api.bittopup.com/naicha'

async function getAxiosData(url, params = {}) {
  try {
    const response = await axios.get(url, { params, timeout: 10000 })
    return response.data.data
  } catch (error) {
    console.error(`Error fetching data from ${url}:`, error)
    return null
  }
}

const apis = [
  'https://searchadvisor.naver.com/indexnow',
  'https://yandex.com/indexnow',
  'https://api.indexnow.org/indexnow',
  'https://search.seznam.cz/indexnow',
]
;(async () => {
  const goodsData = await getAxiosData(`${BASE_URL}/open/allGoods?isPure=1`)
  const goodsCollections = chunk(goodsData, 100)

  for (const api of apis) {
    for (const goodsList of goodsCollections) {
      try {
        const urls = goodsList
          .map(({ urlName }) => {
            return [
              'goods',
              'ru/goods',
              'ar/goods',
              'zh/goods',
              'zh-hk/goods',
              'ko/goods',
              'es/goods',
              'pt/goods',
              'id/goods',
              'hi/goods',
              'ms/goods',
            ].map((suffix) => `https://bittopup.com/${suffix}/${urlName}`)
          })
          .flat(Infinity)
        console.log(urls.slice(0, 10))
        const res = await axios.post(api, {
          host: 'bittopup.com',
          key: '4525405b409b484e9505779fa3a51e15',
          keyLocation: 'https://bittopup.com/4525405b409b484e9505779fa3a51e15.txt',
          urlList: urls,
        })
        console.log(res.data)
      } catch (e) {
        console.log(e.response.data)
      }
    }
  }
})()
